package com.example.demo.config.security.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * spring cloud security 自定义异常处理,非授权、权限拒绝的异常
 */
@Slf4j
@Configuration
public class Oauth2ExceptionTranslatorConfiguration {

    @Bean
    public WebResponseExceptionTranslator oauth2ResponseExceptionTranslator() {
        return new DefaultWebResponseExceptionTranslator() {

            @Override
            public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {

                int status = 500;

                ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);

                HttpStatus statusCode = responseEntity.getStatusCode();
                Throwable temp = e.getCause();
                if("Token was not recognised".equals(e.getMessage())){
                    //无法识别的token
                    statusCode = HttpStatus.OK;
                    status = 2301;
                }
                OAuth2Exception body = responseEntity.getBody();

                body.addAdditionalInformation("code", String.valueOf(403));
                body.addAdditionalInformation("message", body.getMessage());

                HttpHeaders headers = new HttpHeaders();
                headers.setAll(responseEntity.getHeaders().toSingleValueMap());

                return new ResponseEntity<>(body, headers, statusCode);

            }
        };
    }

}